<template>
  <div class="tattoo-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>纹身产品列表</span>
          <el-button type="primary" @click="handleAdd">新增产品</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline>
        <el-form-item label="产品标题">
          <el-input v-model="searchForm.title" placeholder="请输入产品标题" clearable />
        </el-form-item>
        <el-form-item label="产品分类">
          <el-select v-model="searchForm.category_id" placeholder="请选择产品分类" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
	  <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
			<el-tab-pane label="User" name="first"></el-tab-pane>
			<el-tab-pane label="Config" name="second"></el-tab-pane>
			<el-tab-pane label="Role" name="third"></el-tab-pane>
			<el-tab-pane label="Task" name="fourth"></el-tab-pane>
		</el-tabs>	
      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="tattoo_id" label="ID" width="80" />
        <el-table-column prop="title" label="产品标题" />
        <el-table-column prop="category_id" label="分类ID" width="100" />
        <el-table-column label="封面图" width="120">
          <template #default="{ row }">
            <el-image
              style="width: 80px; height: 80px"
              :src="row.logo"
              :preview-src-list="[row.logo]"
              fit="cover"
              preview-teleported
              hide-on-click-modal
            />
          </template>
        </el-table-column>
        <el-table-column label="图集" width="120">
          <template #default="{ row }">
            <el-popover
              placement="right"
              width="auto"
              trigger="click"
            >
              <template #reference>
                <el-button type="primary" size="small">查看图集</el-button>
              </template>
              <div class="image-gallery">
                <el-image
                  v-for="(img, index) in getImageList(row.image)"
                  :key="index"
                  style="width: 100px; height: 100px; margin: 5px"
                  :src="img"
                  :preview-src-list="getImageList(row.image)"
                  fit="cover"
                  preview-teleported
                  hide-on-click-modal
                />
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="120">
          <template #default="{ row }">
            ¥{{ row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_del ? 'danger' : 'success'">
              {{ row.is_del ? '已删除' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="50%"
    >
      <el-form :model="formData" label-width="120px">
        <el-form-item label="产品标题">
          <el-input v-model="formData.title" />
        </el-form-item>
        <el-form-item label="产品分类">
          <el-select v-model="formData.category_id" placeholder="请选择产品分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="封面图">
          <el-upload
            action="/api/upload"
            list-type="picture-card"
            :file-list="logoFileList"
            :on-success="handleLogoUploadSuccess"
            :before-upload="beforeUpload"
            :limit="1"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="图集">
          <el-upload
            action="/api/upload"
            list-type="picture-card"
            :file-list="galleryFileList"
            :on-success="handleGalleryUploadSuccess"
            :before-upload="beforeUpload"
            :on-remove="handleGalleryRemove"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="价格">
          <el-input-number v-model="formData.price" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="formData.sort" :min="0" />
        </el-form-item>
        <el-form-item label="产品描述">
          <el-input v-model="formData.content" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'

// 类型定义
interface TattooItem {
  id: number
  tattoo_id: number
  category_id: number
  title: string
  sort: number
  created_at: string
  is_del: number
  content: string
  update_at: string
  image: string // 图集，多个图片URL用逗号分隔
  logo: string // 封面图
  price: number
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

interface SearchForm {
  title: string
  category_id: number | null
}

// 数据状态
const tableData = ref<TattooItem[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增产品')
const formData = reactive<Partial<TattooItem>>({
  title: '',
  category_id: null,
  price: 0,
  sort: 0,
  content: '',
  logo: '',
  image: ''
})

// 上传相关
const logoFileList = ref<UploadUserFile[]>([])
const galleryFileList = ref<UploadUserFile[]>([])

// 分页配置
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive<SearchForm>({
  title: '',
  category_id: null
})

// 模拟分类选项
const categoryOptions = [
  { value: 1, label: '传统纹身' },
  { value: 2, label: '水彩纹身' },
  { value: 3, label: '几何纹身' },
  { value: 4, label: '字母纹身' }
]

// 将图集字符串转换为数组
const getImageList = (imageStr: string) => {
  return imageStr ? imageStr.split(',') : []
}

// 生命周期钩子
onMounted(() => {
  fetchData()
})

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    // 这里替换为实际的API调用
    // const res = await getTattooList({
    //   page: pagination.currentPage,
    //   pageSize: pagination.pageSize,
    //   ...searchForm
    // })
    
    // 模拟API返回数据
    const mockData: TattooItem[] = Array.from({ length: 25 }, (_, i) => ({
      id: i + 1,
      tattoo_id: 1000 + i,
      category_id: Math.floor(Math.random() * 4) + 1,
      title: `纹身作品 ${i + 1}`,
      sort: i + 1,
      created_at: new Date().toISOString(),
      is_del: i % 5 === 0 ? 1 : 0,
      content: `这是第 ${i + 1} 个纹身作品的详细描述`,
      update_at: new Date().toISOString(),
      image: Array.from({ length: 3 }, (_, j) => `https://picsum.photos/300/200?random=${i}${j}`).join(','),
      logo: `https://picsum.photos/150/150?random=${i}`,
      price: Math.floor(Math.random() * 1000) + 100
    }))
    
    // 模拟筛选
    let filteredData = [...mockData]
    if (searchForm.title) {
      filteredData = filteredData.filter(item => 
        item.title.includes(searchForm.title)
      )
    }
    if (searchForm.category_id) {
      filteredData = filteredData.filter(item => 
        item.category_id === searchForm.category_id
      )
    }
    
    // 模拟分页
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    tableData.value = filteredData.slice(start, end)
    pagination.total = filteredData.length
    
    // 实际API调用时使用下面的代码
    // tableData.value = res.data.list
    // pagination.total = res.data.total
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  fetchData()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  fetchData()
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.title = ''
  searchForm.category_id = null
  handleSearch()
}

// 新增产品
const handleAdd = () => {
  dialogTitle.value = '新增产品'
  Object.assign(formData, {
    title: '',
    category_id: null,
    price: 0,
    sort: 0,
    content: '',
    logo: '',
    image: ''
  })
  logoFileList.value = []
  galleryFileList.value = []
  dialogVisible.value = true
}

// 编辑产品
const handleEdit = (row: TattooItem) => {
  dialogTitle.value = '编辑产品'
  Object.assign(formData, row)
  
  // 设置封面图上传列表
  logoFileList.value = row.logo ? [{
    name: '封面图',
    url: row.logo
  }] : []
  
  // 设置图集上传列表
  galleryFileList.value = getImageList(row.image).map((img, index) => ({
    name: `图集图片${index + 1}`,
    url: img
  }))
  
  dialogVisible.value = true
}

// 删除产品
const handleDelete = (row: TattooItem) => {
  ElMessageBox.confirm('确定要删除该产品吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 这里替换为实际的API调用
      // await deleteTattoo(row.id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交表单
const submitForm = async () => {
  try {
    // 这里替换为实际的API调用
    // if (formData.id) {
    //   await updateTattoo(formData)
    // } else {
    //   await createTattoo(formData)
    // }
    ElMessage.success(dialogTitle.value + '成功')
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error(dialogTitle.value + '失败')
    console.error(error)
  }
}

// 封面图上传成功
const handleLogoUploadSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // 这里根据实际API返回结构调整
  formData.logo = URL.createObjectURL(uploadFile.raw!)
}

// 图集上传成功
const handleGalleryUploadSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // 这里根据实际API返回结构调整
  const newImage = URL.createObjectURL(uploadFile.raw!)
  const currentImages = formData.image ? formData.image.split(',') : []
  currentImages.push(newImage)
  formData.image = currentImages.join(',')
}

// 图集删除
const handleGalleryRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  const removedUrl = uploadFile.url || ''
  const currentImages = formData.image ? formData.image.split(',') : []
  const newImages = currentImages.filter(img => img !== removedUrl)
  formData.image = newImages.join(',')
}

// 上传前校验
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}
</script>

<style scoped>
.tattoo-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  max-height: 500px;
  overflow-y: auto;
}
</style>